利用Python中的元类实现缓存实例(cached instance)

关于缓存实例(cached instance),可以参考Python中的弱引用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import weakref
class Cached(type):
def __init__(self, *args, **kwargs):
super(Cached, self).__init__(*args, **kwargs)
# 建立一个value为弱引用的对象
self.__cache = weakref.WeakValueDictionary()
def __call__(self, *args):
if args in self.__cache:
return self.__cache[args]
else:
# 注意,这里的self为Spam.Spam已经通过元类创建了__cache对象
obj = super(Cached, self).__call__(*args)
self.__cache[args] = obj
return obj
class Spam(metaclass=Cached):
def __init__(self, name):
print('Creating Spam({!r})'.format(name))
self.name = name
if __name__ == '__main__':
a = Spam('foo')
b = Spam('bar')
print('a is b:', a is b)
c = Spam('foo')
print('a is c:', a is c)

文章目录
|